package com.icinfo.cloud.provider.common.utils;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.icinfo.framework.common.web.Result;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 描述：excel导出工具类
 *
 * @Author zhengqiang
 * @Date 2023/1/4 21:03
 **/
public class ExcelUtils {

    /**
     * 描述： excel导出
     *
     * @author: zhengqiang
     * @date: 2023/1/11
     * @param: dataList 数据列表
     * @param: headList 字段名称列表
     * @param: fileName 文件名称
     * @param: response
     * @return {@link Result}
     **/
    public static Result ExportList(List dataList, List<Map<String, String>> headList, String fileName, HttpServletResponse response) throws Exception{
        //在内存里做操作，保存到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        headList.forEach(headMap -> {
            Map.Entry<String, String> next = headMap.entrySet().iterator().next();
            writer.addHeaderAlias(next.getKey(), next.getValue());
        });

        //一次性写出list内的对象的Excel，使用默认样式，强制输出标题
        writer.write(dataList,true);
        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filName= URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+filName+".xls");

        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        return Result.success("success");
    }

}
